package com.liser.print.bluetooth.receiver;

import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;

import com.liser.print.bluetooth.callback.BaseCallback;

/**
 * 蓝牙连接广播
 *
 * @author LISER
 * @date 2020/01/14
 */
public class BtConnectReceiver extends BroadcastReceiver {

    public static final String TAG = BtConnectReceiver.class.getName();

    private BaseCallback mBaseCallback;

    public BtConnectReceiver(Context context, BaseCallback baseCallback) {
        mBaseCallback = baseCallback;
        IntentFilter filter = new IntentFilter();

        //设备建立连接
        filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
        //设备断开连接
        filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);

        context.registerReceiver(this, filter);
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        BluetoothDevice dev;
        if (action == null) {
            return;
        }
        switch (action) {
            // 建立连接
            case BluetoothDevice.ACTION_ACL_CONNECTED:
                Log.d(TAG, "蓝牙连接成功");
                dev = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                mBaseCallback.onConnect(dev);
                break;

            // 断开连接
            case BluetoothDevice.ACTION_ACL_DISCONNECTED:
                dev = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                Log.w(TAG, "蓝牙连接断开");
                mBaseCallback.onDisconnect(dev);
                break;

            default:
                break;
        }
    }
}